package com.jlboot.app.admin.controller;

import com.jfinal.aop.Before;
import com.jlboot.app.admin.base.BaseController;
import com.jlboot.app.admin.interceptor.AdminGlobalInterceptor;
import com.jlboot.core.consts.Consts;
import com.jlboot.core.consts.CoreResponseCode;
import com.jlboot.core.exception.JlLogicException;
import com.jlboot.core.model.DataMap;
import com.jlboot.core.model.LoginUser;
import com.jlboot.core.util.LoginUtil;
import com.jlboot.model.po.sys.SysOnline;
import com.jlboot.model.po.sys.SysUser;
import com.jlboot.core.ConfigUtil;
import com.jlboot.core.Results;
import com.jlboot.core.id.UUIDHex;
import com.jlboot.core.json.Jmode;
import com.jlboot.core.json.JsonResult;
import com.jlboot.core.lc.Aes;
import com.jlboot.core.lc.Pwd;
import com.jlboot.core.util.ClientUtil;
import com.jlboot.core.form.FormData;
import com.jlboot.app.admin.interceptor.Admins;

import com.jlboot.core.cache.SysConfigCache;
import com.jlboot.app.admin.util.SysUserUtil;
import com.jlboot.app.admin.controller.weixin.common.WxTool;
import com.jfinal.aop.Clear;
import com.jlboot.model.po.sys.SysWorkLog;
import lombok.extern.slf4j.Slf4j;


/**
 * 本类为系统登陆类，密码修改类
 * Created by 51594 on 2019/10/21.
 */
@Slf4j
public class LoginController extends BaseController {

    @Clear
    public void index() {

        String TestAdmin = ConfigUtil.getProperty("TEST_USER", "");
        String TestPwd = ConfigUtil.getProperty("TEST_PWD", "");
        setForm(FormData.n().addData("username", TestAdmin).addData("password", TestPwd));
        setAttr("sys_title", SysConfigCache.getConfigValue("sys_title"));
        setAttr("version", SysConfigCache.getConfigValue("version"));
        if (SysConfigCache.getConfigIntValue("wx_login") == 1) {
            render("login_wx.html");
        } else {
            render("login.html");
        }

    }

    /**
     * 修改密码页面
     */
    @Admins(roles = "login", name = "修改密码页面", log = true)
    public void ChangePwd() {
        setForm(FormData.n().addData("oldpwd", "").addData("newpwd", "").addData("newpwd1", ""));
        // setForm(FormData.n());
        render("ChangePwd.html");
    }


    /**
     * 退出系统
     */
    @Clear
    public void logout() {
        try{
            LoginUtil.logout();
        }catch (Exception e){
            //如果是无效Token 直接转到登录页面
        }
        redirect(ConfigUtil.getWebAdminLoginPath());
    }

    /**
     * 验证登陆
     */
    @Clear
    @Before(AdminGlobalInterceptor.class)
    public void ValidateLoginApi() {
        DataMap data = getDatas(getParaStr("postData", ""));
        JsonResult jr = JsonResult.ok();
        String username1 = data.getBaseStr("username");
        String login_name = Aes.aesDecrypt2(username1);
        if (login_name.equals(username1)) login_name = Aes.aesDecrypt(username1);

        //////////////////////////////验证码/////////////////////////////
        String validateCode=(String) LoginUtil.getAnonTokenSessionValue(Consts.login_spec_captcha_code);
        if(validateCode==null||!validateCode.equals(data.getStr("vercode", ""))){
            throw new JlLogicException(CoreResponseCode.VER_CODE_ERR.getCode(),CoreResponseCode.VER_CODE_ERR.getName());
        }

        /////////////////////////////验证码结束//////////////////
        String password1 = data.getBaseStr("password");
        String password = Aes.aesDecrypt2(password1);
        if (password.equals(password1)) password = Aes.aesDecrypt(password1);
        if (password.length() < 8) {
            jr = JsonResult.fail( "密码必须是8位及以上");
        } else if (!Pwd.match_Aa18(password)) {
            jr = JsonResult.fail( "密码必须是大小写字母数字组合");
        } else {
            String ip = ClientUtil.getIp(getRequest());
            String os = ClientUtil.getClientOS(getRequest());
            String browser = ClientUtil.getClientBrowser(getRequest());


            String sql = "select * from sys_user where del_tag=0 and login_id=?";
            SysUser su = SysUser.dao.findFirst(sql, login_name);
            if (su != null) {
                String user_id = su.mod.getStr("id");
                String dept_id = su.mod.getStr("dept_id");
                String email = su.mod.getStr("email");
                int lock_tag = su.mod.getInt("lock_tag");
                int del_tag = su.mod.getInt("del_tag");
                String user_pwd=su.mod.getStr("user_pwd");
                String salt=su.mod.getStr("salt");

                //判断账号密码
                String enPassword=SysUserUtil.encryptUserPwd(password,salt);
                if(!enPassword.equals(user_pwd)){
                    throw new JlLogicException(CoreResponseCode.PASSWORD_ERR.getCode(),CoreResponseCode.PASSWORD_ERR.getName());
                }

                //判断状态
                if (lock_tag == 1) {
                    throw new JlLogicException(CoreResponseCode.ACCOUNT_LOCK.getCode(),CoreResponseCode.ACCOUNT_LOCK.getName());
                } else if (del_tag == 1) {
                    throw new JlLogicException(CoreResponseCode.UN_KNOW_ERR.getCode(),CoreResponseCode.UN_KNOW_ERR.getName());
                }

                LoginUser wu = new LoginUser();
                wu.setUserId(user_id);
                wu.setLoginName(login_name);
                wu.setEmail(email);

                LoginUtil.login(wu.getUserId(),wu);

                SysOnline.dao.saveLogin(LoginUtil.getTokenSessId(), LoginUtil.getUserId(), ip, os, browser);//

            } else {
                //账号不存在，不要提示账号不存在，提示账号或密码错误，会更安全一点
                throw new JlLogicException(CoreResponseCode.PASSWORD_ERR.getCode(),CoreResponseCode.PASSWORD_ERR.getName());
            }


        }

        /////记录日志
        SysWorkLog.dao.saveLoginLog(getRequest(), jr.getCode(), jr.getMsg(), login_name);
        renderJson(jr);
    }

    /**
     * 修改密码Api
     */
    @Admins(roles = "login", name = "修改密码Api", log = true)
    public void ChangePwdApi() {
        DataMap data = getDatas(getParaStr("postData", ""));
        String oldPassword1 = data.getBaseStr("oldPassword", "");//
        String password1 = data.getBaseStr("password");//
        String repassword1 = data.getBaseStr("repassword");//
        String password = Aes.aesDecrypt(password1);
        String oldPassword = Aes.aesDecrypt(oldPassword1);
        String repassword = Aes.aesDecrypt(repassword1);
        if (password.length() < 8) {
            renderJson(JsonResult.fail( "新密码必须是8位及以上-" + password1 + "-"));
        } else if (!Pwd.match_Aa18(password)) {
            renderJson(JsonResult.fail( "新密码必须是大小写字母数字组合"));
        } else if (password.equals(repassword)) {
            String userId = LoginUtil.getLoginId();

            SysUser su = SysUser.dao.findById(userId);
            if (su == null) {
                renderJson(JsonResult.fail( "用户不存在"));
            } else {
                String user_pwd=su.mod.getStr("user_pwd");
                String salt=su.mod.getStr("salt");
                if(SysUserUtil.checkPassword(oldPassword,salt,user_pwd)){

                    boolean flag=SysUserUtil.resetPassword(userId,password);
                    if (flag) {
                        renderJson(JsonResult.fail( "密码修改成功"));
                    } else {
                        renderJson(JsonResult.fail( "密码修改失败"));
                    }
                }else{
                    renderJson(JsonResult.fail( "旧密码不正确"));
                }

            }
        } else {
            renderJson(JsonResult.fail( "两次密码不一致"));
        }
    }

    /**
     * 输出登陆二维码
     */
    @Clear
    public void getWxQrLoginApi() {
        String qr_uuid = UUIDHex.getUUIDHex();
        Results result = WxTool.getWxQrCodeUrl("{type:'web_login',qr_uuid:'" + qr_uuid + "'}");
        result.setKeystring(qr_uuid);
        renderJson(result);
    }

//    /**
//     * 输出登陆二维码
//     */
//    @Clear
//    public void getWxQrLoginStatusApi() {
//        JsonResult jr = JsonResult.n();
//        String qr_uuid = getParaStr("qr_uuid", "");
//        if (qr_uuid.length() > 20) {
//            WxMember member = WxMember.dao.findFirst("select * from wx_member where qr_uuid=? ", qr_uuid);
//            if (member != null) {
//                Long userId = member.mod.getLong("id", 0L);
//                String ip = ClientUtil.getIp(getRequest());
//                String os = ClientUtil.getClientOS(getRequest());
//                String browser = ClientUtil.getClientBrowser(getRequest());
//                jr = LoginUtil.getInstance().validateUserPwdJwt(userId, ip);
//                if (jr.getCode() == 0) {
//                    String jwt = jr.getExtra();
//                    LoginUtil.setJwt(getResponse(), jwt);
//
//                    ////////////////////写登陆日志/////////////////
//                    String sessId = JwtUtil.getJwtInfo(jwt).getId();
//                    /////////////////////写在线用户////////////////////////
//                    SysOnline.dao.saveLogin(sessId, userId, ip, os, browser);//
//                }
//                renderJson(jr);
//                return;
//            }
//        }
//        renderJson(JsonResult.n(99, ""));
//    }

    /**
     * 输出 随机密码
     */
    @Clear
    public void getRandomPwdApi() {
        renderJson(Jmode.n().set("pwd", Pwd.getRandomPwd()));
    }
}
